from pydantic import BaseModel, Field, ConfigDict, field_validator
from typing import Optional
from datetime import datetime
import re


class SiteInfoCreate(BaseModel):
    """
    创建/保存网站基础信息的请求模型
    """
    site_name: str
    site_description: Optional[str] = None
    site_keywords: Optional[str] = None
    logo_url: Optional[str] = None
    icp_number: Optional[str] = None
    contact_email: Optional[str] = None
    service_phone: Optional[str] = None
    company_address: Optional[str] = None
    is_active: bool = True


class SiteInfoUpdate(BaseModel):
    """
    更新网站基础信息的请求模型（全部字段可选）
    """
    site_name: Optional[str] = None
    site_description: Optional[str] = None
    site_keywords: Optional[str] = None
    logo_url: Optional[str] = None
    icp_number: Optional[str] = None
    contact_email: Optional[str] = None
    service_phone: Optional[str] = None
    company_address: Optional[str] = None
    is_active: Optional[bool] = None

    @field_validator('contact_email')
    def validate_email(cls, v):
        """
        简易邮箱格式校验，避免依赖 email-validator
        """
        if v is None or v == "":
            return v
        pattern = r"^[^@\s]+@[^@\s]+\.[^@\s]+$"
        if not re.match(pattern, v):
            raise ValueError('邮箱格式不正确')
        return v

    @field_validator('service_phone')
    def validate_phone(cls, v):
        """
        简易电话格式校验，支持 11 位手机号或区号-座机
        """
        if v is None or v == "":
            return v
        mobile = r"^\d{11}$"
        landline = r"^\d{3,4}-?\d{7,8}$"
        if not (re.match(mobile, v) or re.match(landline, v)):
            raise ValueError('电话格式不正确')
        return v


class SiteInfoResponse(BaseModel):
    """
    网站基础信息响应模型
    """
    id: int
    site_name: str
    site_description: Optional[str]
    site_keywords: Optional[str]
    logo_url: Optional[str]
    icp_number: Optional[str]
    contact_email: Optional[str]
    service_phone: Optional[str]
    company_address: Optional[str]
    is_active: bool
    created_at: str = Field(..., description="创建时间，格式：YYYY-MM-DD HH:MM:SS")
    updated_at: str = Field(..., description="更新时间，格式：YYYY-MM-DD HH:MM:SS")

    model_config = ConfigDict(from_attributes=True)

    @classmethod
    def from_orm(cls, obj):
        """
        从 ORM 对象创建响应模型，并格式化时间字段
        """
        return cls(
            id=obj.id,
            site_name=obj.site_name,
            site_description=getattr(obj, 'site_description', None),
            site_keywords=getattr(obj, 'site_keywords', None),
            logo_url=getattr(obj, 'logo_url', None),
            icp_number=getattr(obj, 'icp_number', None),
            contact_email=getattr(obj, 'contact_email', None),
            service_phone=getattr(obj, 'service_phone', None),
            company_address=getattr(obj, 'company_address', None),
            is_active=bool(getattr(obj, 'is_active', True)),
            created_at=obj.created_at.strftime("%Y-%m-%d %H:%M:%S") if getattr(obj, 'created_at', None) else "",
            updated_at=obj.updated_at.strftime("%Y-%m-%d %H:%M:%S") if getattr(obj, 'updated_at', None) else "",
        )
